import psycopg2


def getConnection():
    conn = psycopg2.connect(database="postgres", user="postgres", password="123456", host="172.26.168.143", port="5432")
    print("Opened database successfully")
    return conn


def insert(sql):
    conn = getConnection()
    cur = conn.cursor()
    try:
        cur.execute(sql)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print("插入数据失败", e)
    finally:
        conn.close()


def select(sql):
    conn = getConnection()
    cur = conn.cursor()
    try:
        cur.execute(sql)
        rows = cur.fetchall()
        return rows
    except Exception as e:
        print("查询数据失败", e)
    finally:
        conn.close()


def update(sql):
    conn = getConnection()
    cur = conn.cursor()
    try:
        cur.execute(sql)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print("更新数据失败", e)
    finally:
        conn.close()


def delete(sql):
    conn = getConnection()
    cur = conn.cursor()
    try:
        cur.execute(sql)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print("删除数据失败", e)
    finally:
        conn.close()
